<?php

namespace App\Http\Controllers\Api\Main;

// use App\Handlers\Wechat\wechatclass as Wechat;
// use App\Handlers\Wechat\errCode;
require app_path().'/Handlers/Wechat/wechatclass.php';
require app_path().'/Handlers/Wechat/errCode.php';

use App\Http\Controllers\Api\Order\NotifyController;
use App\Http\Models\User\UserBaseModel;
use App\Models\Balance;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Redis;
use PHPUnit\Framework\BaseTestListener;

class PayController extends ApiController
{
	protected $weObj;

	public function __construct()
	{
		if(!$this->weObj){
			$this->getObj();
		} 
	}

	public function getObj(){
		$options = array(
			'token'=>'',	//填写应用接口的Token
			'encodingaeskey'=>'',//填写加密用的EncodingAESKey
			'appid'=>config('pay.wechat_option.Appid'),	//填写高级调用功能的appid
			'appsecret'=>config('pay.wechat_option.Appsecret'), //填写高级调用功能的密钥
		);
		$this->weObj = new \Wechat($options);
	}

	//获取用户信息，微信登录授权
    public function getUserInfo($urls){
        $userInfo = '';
        if(empty($userInfo)){
            if (!isset($_GET['code']))
            {
                //触发微信返回code码
                $url = $this->weObj->getOauthRedirect($urls,'STATE','snsapi_base');
                Header("Location: $url");
                exit;
            }else {
                //获取code码，以获取openid
                $result = $this->weObj->getOauthAccessToken();
                // $userInfo = $this->weObj->getOauthUserinfo( $result['access_token'],$result['openid']);
                return ['openid'=>$result['openid']];
            }
        }
        return $userInfo;
    }


    public function getOpenid()
    {
        $url = url()->full();
        $data = $this->getUserInfo($url);
//        if($request->has('user_id') && !empty($data['openid'])){
//            $user_model = User::find($request->input('user_id'));
//            $user_model -> open_id = $data['openid'];
//            $user_model -> save();
//        }
//        return self::response(null,self::SUC_CODE,'成功获取openId');
        return $data['openid'];
    }


    public function getUserWxInfo(Request $request)
    {
        $url = url()->full();
//        $data = $this->getUserInfo($url);
        $url = $this->weObj->getOauthRedirect($url,'STATE','snsapi_base');
        return self::response(['url'=>$url],self::SUC_CODE);
        $openid             = $data;
//        $flag =  UserBaseModel::updateUser($input['uid'],['open_id'=>$openid]);
        return self::response(['openid'=>$openid],self::SUC_CODE);
    }



    
    #微信支付
    public function payByWechat(Request $request)
    {
        $order_id           = intval($request->order_id);
        if(!$order_id){
            return reself::response(null,self::ERROR_CODE,'请填写订单id');
        }
        $openid             = $request->openid;
        $result             = DB::table('orders')->where('id','=',$order_id)->first();
    	$order              = [
    		'out_trade_no'  => $result->order_sn,
    		'total_feel'    => $result->money_paid*100,
    		'body'          => '商城商品支付',
    		'openid'        => $openid
    	];
    	$wechatOrder = app('wechat_pay')->mp($order);
        return $wechatOrder;
    }


    public function WxPay(Request $request)
    {
        $openid             = $this->getOpenid();
        $order_sn = 'H_V1'.mt_rand(1,1000).time();
        $wechatOrder = app('wechat_pay')->mp([
            'out_trade_no' => $order_sn,
            'total_fee'    => 0.01*100,
            'body'         => '归仁生物-医药家用商品',
            'openid'       => $openid,
        ])->toArray();
        //需要跳转到微信支付页面
        return redirect(config('pay.wap_pay_url').'/?jsApiParameters='.json_encode($wechatOrder).'#/wxpay');
    }





    public function notify()
    {
    	$data = app('wechat_pay')->verify();
    	// 找到对应的订单
        $Notify = new NotifyController();
        $flag   = $Notify->Notify($data->out_trade_no);
        // 订单不存在则告知微信支付
        if (!$flag) {
            return 'fail';
        }
    	return app('wechat_pay')->success();
    }

    /**支付参数的获取(在用户已经绑定open_id的情况下)
     * @param Request $request
     * @return mixed
     */
    public function payParams(Request $request,Order $orderModel)
    {
        if(empty($request->input('open_id'))){
            return self::response(null,self::ERROR_CODE,'用户不能为空');
        }

        $user_model = User::where('open_id','=',$request->input('open_id'))->first();

        if(empty($user_model)){
            return self::response(null,self::ERROR_CODE,'非法用户');
        }

        $order_sn = $request -> input('order_sn');

        if(empty($order_sn)){
            return self::response(null,self::ERROR_CODE,'订单编号不能为空');
        }

        $order_model = $orderModel -> getOrderBaseInfoByOrderSn($order_sn);
        if($type = self::getOrderType($order_sn)){
            if($type == 1){
                $total_fee = $order_model['money_paid'];
            }else if($type ==2 || $type ==3){
                $total_fee = $order_model['total_amount'];
            }
        }
        //没有获取到总金额
        if(empty($order_model) || !isset($total_fee)){
            return self::response(null,self::ERROR_CODE,'无效的订单编号!');
        }

//        $total_fee = 0.01;
        $wechatOrder = app('wechat_pay')->mp([
            'out_trade_no' =>  $order_sn,
            'total_fee'    =>  (int) ($total_fee*100),
            'body'         => 'youyike-智能盒子购物',
            'openid'       =>  $request->input('open_id'),
        ])->toArray();

        return self::response(['jsApiParameters'=>$wechatOrder],self::SUC_CODE,'获取支付参数成功');
    }


    /**前端传过来code ，后端获取openId并存入用户表
     * @param Request $request
     * @return mixed|string
     */
    public function wap_open_id(Request $request)
    {
        $url = url()->full();
        $userInfo = '';
        if(empty($userInfo)){
            if (!isset($_GET['code']))
            {
                //触发微信返回code码
                $url = $this->weObj->getOauthRedirect($url,'STATE','snsapi_base');
                Header("Location: $url");
                exit;
            }else {
                //获取code码，以获取openid
                $data = $this->weObj->getOauthAccessToken();
                if($request->has('user_id') && !empty($data['openid'])){
                    $user_model = User::find($request->input('user_id'));
                    $user_model -> open_id = $data['openid'];
                    $user_model -> save();
                }
                return self::response(['open_id'=>$data['openid']],self::SUC_CODE,'成功获取openId');
            }
        }


        return $userInfo;
    }

    /**前端注册的时候跳转到服务器获取openId，服务器再重定向到注册页面，传递OpenId
     * @param Request $request
     * @return mixed|string
     */
    public function wap_regist_get_open_id(Request $request)
    {
        if (!isset($_GET['code']))
        {
            $url = url()->full();
            $url = $this->weObj->getOauthRedirect($url,'STATE','snsapi_base');
            Header("Location: $url");
            exit;
        }else {
            //获取code码，以获取openid
            $result = $this->weObj->getOauthAccessToken();
            $openId = $result['openid'];
            $wapcallbackurl = $request->input('wapcallbackurl','http://shop.slf0319.com/');
            $hash = $request->input('hash','register');
            $wapcallbackurl = trim($wapcallbackurl,'/').'/#/'.trim($hash,'/');
//            $urlArr = parse_url($wapcallbackurl);
            $redirectUrl = $wapcallbackurl.'/'.$openId;
            return redirect($redirectUrl);
        }
    }


//    public function addRecord()
//    {
//        Balance::addShoppingRecord('H901776162194116_V1');
//    }


}
